package com.yhx.leetcode.java;

/**
 * @Author: mishuai
 * @Date: 2020/7/6 2:24 下午
 */
public class LeetCode13 {


    public static void main(String[] args) {
        System.out.println(romanToInt("MCMXCIV"));
    }

    static int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

    static String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};



    public static int romanToNum(String roman){

        int result=0;
        if(roman == null || roman.length() == 0) return 0;
        int flag=0;

        while(flag < roman.length()){
            for(int i=0;i<symbols.length;i++){
                String str=symbols[i];
                int start=flag;
                int end=flag+str.length();
                String s=roman.substring(start,end-1);
                if(s.equals(symbols[i])){
                    result +=values[i];
                    flag  =flag + str.length();
                }
            }
        }
        return result;
    }




    public static int romanToInt(String s) {
        int sum = 0;
        int preNum = getValue(s.charAt(0));
        for(int i = 1;i < s.length(); i ++) {
            char c=s.charAt(i);
            int num = getValue(c);
            if(preNum < num) {
                sum -= preNum;
            } else {
                sum += preNum;
            }
            preNum = num;
        }
        sum += preNum;
        return sum;
    }

    private static int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }

}
